package com.walkline.screen;

import java.util.Hashtable;
import java.util.Vector;

import net.rim.device.api.system.ApplicationDescriptor;
import net.rim.device.api.system.Characters;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.FontFamily;
import net.rim.device.api.ui.FontManager;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.Ui;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.XYEdges;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.Menu;
import net.rim.device.api.ui.component.ObjectChoiceField;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.util.StringProvider;

import com.walkline.app.TravelAssistantAppConfig;
import com.walkline.travelassistant.BasicAsyncCallback;
import com.walkline.travelassistant.TravelAssistantSDK;
import com.walkline.travelassistant.inf.Direction;
import com.walkline.travelassistant.inf.Location;
import com.walkline.travelassistant.inf.SuggestionItem;
import com.walkline.travelassistant.inf.SuggestionResult;
import com.walkline.util.Enumerations.TravelMode;
import com.walkline.util.Function;
import com.walkline.util.ui.ForegroundManager;
import com.walkline.util.ui.ListStyleButtonField;
import com.walkline.util.ui.ListStyleButtonSet;
import com.walkline.util.ui.MyTextField;
import com.walkline.util.ui.VerticalButtonFieldSet;

public final class TravelAssistantScreen extends MainScreen
{
	private TravelAssistantSDK _travelAssistant = TravelAssistantSDK.getInstance();
	private ForegroundManager _foreground = new ForegroundManager(0);
	private ListStyleButtonSet _startListSet = new ListStyleButtonSet(true);
	private ListStyleButtonSet _finishListSet = new ListStyleButtonSet(true);
	private ButtonField _btnLocation;
	private MyTextField _editStart = new MyTextField(MyTextField.MODE_START);
	private MyTextField _editFinish = new MyTextField(MyTextField.MODE_FINISH);
	private ObjectChoiceField _choiceTravelMode;

	private String _city_code = "";
	private String _origin_city_code = "";
	private String _destination_city_code = "";

    public TravelAssistantScreen()
    {
    	super (NO_VERTICAL_SCROLL | USE_ALL_HEIGHT | NO_SYSTEM_MENU_ITEMS);

    	setDefaultClose(false);

    	String appVer = "v" + ApplicationDescriptor.currentApplicationDescriptor().getVersion();
        setTitle(TravelAssistantAppConfig.APP_TITLE + " - " + appVer);

		try {
			FontFamily family = FontFamily.forName("BBGlobal Sans");
			Font appFont = family.getFont(Font.PLAIN, 8, Ui.UNITS_pt);
			FontManager.getInstance().setApplicationFont(appFont);
		} catch (ClassNotFoundException e) {}

		createUI();

		UiApplication.getUiApplication().invokeLater(new Runnable()
		{
			public void run()
			{
				_travelAssistant.convertIp2Location(new ConvertIp2LocationCallback(), null);
			}
		});
    }

    private void createUI()
    {
    	VerticalButtonFieldSet vbfLocation = new VerticalButtonFieldSet(USE_ALL_WIDTH);
        _btnLocation = new ButtonField("正在获取当前城市，请稍候....", ButtonField.CONSUME_CLICK | ButtonField.NEVER_DIRTY);

    	XYEdges edges = new XYEdges(5, 5, 5, 5);
    	//_editStart.setText("黄河道桥-公交车站");
        _editStart.setPadding(edges);
        _editStart.setMargin(edges);
        _editStart.setChangeListener(new FieldChangeListener()
        {
			public void fieldChanged(Field field, int context)
			{
				if (context == MyTextField.CLICKED)
				{
					_travelAssistant.querySuggestLocation(_editStart.getText(), getCityCode(), new SuggestLocationCallback(0), null);
				}
			}
		});
        //_editFinish.setText("天津大悦城南区");
        _editFinish.setPadding(edges);
        _editFinish.setMargin(edges);
        _editFinish.setChangeListener(new FieldChangeListener()
        {
			public void fieldChanged(Field field, int context)
			{
				if (context == MyTextField.CLICKED)
				{
					_travelAssistant.querySuggestLocation(_editFinish.getText(), getCityCode(), new SuggestLocationCallback(1), null);
				}
			}
		});

        _choiceTravelMode = new ObjectChoiceField("出行方式：", TravelMode.choicesMode, TravelMode.DEFAULT_MODE);

        VerticalButtonFieldSet vbfQuery = new VerticalButtonFieldSet(USE_ALL_WIDTH);
        ButtonField btnQuery = new ButtonField("查询", ButtonField.CONSUME_CLICK | ButtonField.NEVER_DIRTY);
        btnQuery.setChangeListener(new FieldChangeListener()
        {
			public void fieldChanged(Field field, int context)
			{
				queryDirection();
			}
		});

        vbfLocation.add(_btnLocation);
        _foreground.add(vbfLocation);
        _foreground.add(_editStart);
        _foreground.add(_editFinish);
        _foreground.add(_choiceTravelMode);
        vbfQuery.add(btnQuery);
        _foreground.add(vbfQuery);
        //_foreground.add(_choiceSource);
        //_foreground.add(_choiceDestination);

        add(_foreground);

        UiApplication.getUiApplication().invokeLater(new Runnable()
        {
			public void run() {_editStart.setFocus();}
		});
    }

    private void queryDirection()
    {
    	Hashtable params = new Hashtable();

    	params.put("mode", TravelMode.choicesModeValue[_choiceTravelMode.getSelectedIndex()]);
    	params.put("region", getCityCode());
    	params.put("origin", _editStart.getText());
    	params.put("origin_region", getOriginCityCode());
    	params.put("destination", _editFinish.getText());
    	params.put("destination_region", getDestinationCityCode());

    	RefreshContentsScreen popupScreen = new RefreshContentsScreen(_travelAssistant, params);
		UiApplication.getUiApplication().pushModalScreen(popupScreen);

		Direction direction = popupScreen.getDirectionResult();

		if (popupScreen != null) {popupScreen = null;}
		if (direction != null && direction.getType() == 2) {refreshDirectionResultList(direction);}
    }

    private void refreshDirectionResultList(Direction direction)
	{
    	UiApplication.getUiApplication().pushScreen(new ShowQueryResultScreen(direction));
//		Vector resultList = null;
//		Route route = null;
//		Scheme scheme = null;
//		Step step;
//		Vector stepWrapper;
//		ListStyleButtonField item;
//
//		if (_directionSet.getManager() == _foreground)
//		{
//			_directionSet.deleteAll();
//			_foreground.delete(_directionSet);
//		}
//
//		if (directionResult.getRoutes().hasScheme())
//		{
//			resultList = directionResult.getRoutes().getSchemes();
//
//			for (int i=0; i<resultList.size(); i++)
//			{
//				scheme = (Scheme) resultList.elementAt(i);
//				item = new ListStyleButtonField(scheme);
//				_directionSet.add(item);
//			}
//		} else {
//			resultList = directionResult.getRoutes().getRoutes();
//			route = (Route) resultList.elementAt(0);
//			stepWrapper = route.getSteps().getSteps();
//
//			_directionSet.add(new LabelField(route.getDistanceStr()));
//
//			for (int i=0; i<stepWrapper.size(); i++)
//			{
//				step = (Step) stepWrapper.elementAt(i);
//				if (step != null)
//				{
//					item = new ListStyleButtonField(step);
//					item.setChangeListener(new FieldChangeListener()
//					{
//						public void fieldChanged(Field field, int context)
//						{
//							if (context != FieldChangeListener.PROGRAMMATIC)
//							{
//							}
//						}
//					});
//
//					_directionSet.add(item);
//				}
//			}
//		}
//
//		if (_directionSet.getManager() == null) {_foreground.add(_directionSet);}
	}

	private void refreshSuggestionResultList(SuggestionResult suggestionResult, final int mode)
	{
		Vector resultList = suggestionResult.getSuggestionResult();
		SuggestionItem result;
		ListStyleButtonField item;

		if (mode == 0)
		{
			if (_startListSet.getManager() == _foreground)
			{
				_startListSet.deleteAll();
				_foreground.delete(_startListSet);
			}
		} else if (mode == 1) {
			if (_finishListSet.getManager() == _foreground)
			{
				_finishListSet.deleteAll();
				_foreground.delete(_finishListSet);
			}
		}

		for (int i=0; i<resultList.size(); i++)
		{
			result = (SuggestionItem) resultList.elementAt(i);
			if (result != null)
			{
				item = new ListStyleButtonField(result);
				item.setChangeListener(new FieldChangeListener()
				{
					public void fieldChanged(Field field, int context)
					{
						if (context != FieldChangeListener.PROGRAMMATIC)
						{
							ListStyleButtonField item;

							if (mode == 0)
							{
								item = (ListStyleButtonField) _startListSet.getFieldWithFocus();
								_editStart.setText(item.getLocationName());
								_foreground.delete(_startListSet);
								_editStart.setFocus();
							} else if (mode == 1) {
								item = (ListStyleButtonField) _finishListSet.getFieldWithFocus();
								_editFinish.setText(item.getLocationName());
								_foreground.delete(_finishListSet);
								_editFinish.setFocus();
							}
						}
					}
				});

				if (mode == 0)
				{
					_startListSet.add(item);	
				} else if (mode == 1) {
					_finishListSet.add(item);
				}
			}
		}

		UiApplication.getUiApplication().invokeLater(new Runnable()
		{
			public void run()
			{
				if (mode == 0)
				{
					if (_startListSet.getManager() == null)
					{
						_foreground.insert(_startListSet, _editStart.getIndex() + 1);
					}					
				} else if (mode == 1) {
					if (_finishListSet.getManager() == null)
					{
						_foreground.insert(_finishListSet, _editFinish.getIndex() + 1);
					}
				}
			}
		});
	}

	class ConvertIp2LocationCallback extends BasicAsyncCallback
	{
		public void onComplete(final Location value, Object state)
		{
			if (value != null)
			{
				UiApplication.getUiApplication().invokeLater(new Runnable()
				{
					public void run()
					{
						if (value.getContentProvince().equals("") && value.getContentCity().equals(""))
						{
							Function.errorDialog("无法定位当前城市，请检查是否已开启VPN，如已开启请关闭后重启本程序！");
						} else {
							_btnLocation.setLabel(value.getContentProvince() + " " + value.getContentCity());
							_city_code = value.getContentCityCode();
						}
					}
				});
			} else {
				Function.errorDialog("no city result!");
			}
		}

		public void onException(Exception e, Object state) {Function.errorDialog(e.toString());}
	}

	class SuggestLocationCallback extends BasicAsyncCallback
	{
		int _mode;

		public SuggestLocationCallback(int mode) {_mode = mode;}
	
		public void onComplete(final SuggestionResult value, Object state)
		{
			if (value != null)
			{
				UiApplication.getUiApplication().invokeLater(new Runnable()
				{
					public void run() {if (value.getSuggestionResultCount() > 0)
					{
						SuggestionItem suggestion = (SuggestionItem) value.getSuggestionResult().elementAt(0);

						if (_mode == 0)
						{
							_origin_city_code = suggestion.getCityId();
							_city_code = _origin_city_code;
						} else if (_mode == 1) {
							_destination_city_code = suggestion.getCityId();
						}

						refreshSuggestionResultList(value, _mode);}
					}
				});
			}
		}

		public void onException(Exception e, Object state) {Function.errorDialog(e.toString());}
	}

	private String getCityCode() {return _city_code;}

	private String getOriginCityCode() {return _origin_city_code;}

	private String getDestinationCityCode() {return _destination_city_code;}

	MenuItem menuExit = new MenuItem(new StringProvider("退出(Q\u0332)"), 10000, 1000)
    {
    	public void run() {Function.showExitDialog();}
    };

    protected void makeMenu(Menu menu, int instance)
    {
    	super.makeMenu(menu, instance);

    	menu.add(menuExit);
    }

	protected boolean keyChar(char key, int status, int time)
    {
		if (!_foreground.getFieldWithFocus().equals(_editStart) && !_foreground.getFieldWithFocus().equals(_editFinish))
		{
			switch (key)
			{
				case Characters.LATIN_CAPITAL_LETTER_Q:
				case Characters.LATIN_SMALL_LETTER_Q:
					Function.showExitDialog();
					return true;
			}
		}

    	return super.keyChar(key, status, time);
    }

    public boolean onClose()
    {
    	UiApplication.getUiApplication().requestBackground();

    	return true;
    }

	protected boolean onSavePrompt() {return true;}
}